/**灾害预防的列表页面 */
<template>
  <div class="app-container">

    <div class="filter-container">
      灾害预防题目：   <el-input v-model="listQuery.title" placeholder="题目" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>

      <!--
      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">
        reviewer
      </el-checkbox> -->
    </div>

    <!-- Note that row-key is necessary to get a correct row order. -->
    <el-table ref="dragTable" v-loading="listLoading" :data="list" row-key="id" border fit highlight-current-row style="width: 100%">

      <el-table-column width="180px" align="center" label="灾害预防编号" prop="disid">
        <template slot-scope="scope">
          <span>{{ scope.row.disid }}</span></template>
      </el-table-column>
      <el-table-column min-width="300px" label="灾害预防题目">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)">{{ scope.row.title }}</span></template>
      </el-table-column>
      <el-table-column min-width="300px" label="灾害预防内容">
        <template slot-scope="scope">
          <span>{{ scope.row.content }}</span></template>
      </el-table-column>
      <el-table-column min-width="300px" label="灾害预防发生位置">
        <template slot-scope="scope">
          <span>{{ scope.row.disarea }}</span></template>
      </el-table-column>
      <el-table-column width="100px" label="创建日期" prop="createdate">

        <template slot-scope="scope">
          <span>{{ scope.row.createdate }}</span></template>
      </el-table-column>
      <el-table-column width="100px" label="发生日期" prop="happendate">

        <template slot-scope="scope">
          <span>{{ scope.row.happendate }}</span></template>
      </el-table-column>
      <el-table-column align="center" label="创建人" width="95">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)">{{ scope.row.duser.userName }}</span></template>
      </el-table-column>
      <el-table-column class-name="status-col" label="所属Team" width="110">
        <template slot-scope="scope">
          <span @click="handleDetail(scope.row)">{{ scope.row.department.deptName }}</span></template>
      </el-table-column>
      <!-- <el-table-column align="center" label="实施单填写人" width="95">
          <template slot-scope="scope">
            <span @click="handleDetail(scope.row)">{{ scope.row.dusere }}</span></template>
        </el-table-column>
        <el-table-column class-name="status-col" label="实施单填写人部门" width="110">
          <template slot-scope="scope">
            <span @click="handleDetail(scope.row)">{{ scope.row.workOrderUserDep.deptName }}</span></template>
        </el-table-column> -->
      <el-table-column align="center" label="裁决状态" width="80" prop="">
        <template slot-scope="scope">

          <span v-if="scope.row.status==1">申请中...</span>
          <span v-if="scope.row.status==0">已删除</span>
          <span v-if="scope.row.status==2">已裁决</span>
          <span v-if="scope.row.status==3">已驳回</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="230">
        <template v-if="scope.row.status==2" slot-scope="scope">

          <el-button type="primary" size="small" @click="handleDelete(scope.row)">删除</el-button>
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">修改</el-button>

        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fechData" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="150px" style="width: 800px; margin-left:50px;">
        <el-row>
          <el-col :span="12">
            <el-form-item label="部门" prop="department">

              <el-autocomplete
                v-model="deptName"
                class="el-input"
                :fetch-suggestions="deptSearchAsync"
                placeholder="请输入部门"
                :trigger-on-focus="false"
                @select="handleSelectTeam"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createdate">
              <el-date-picker v-model="temp.createdate" type="datetime" value-format="yyyy-MM-dd hh:mm:ss" placeholder="请选择日期" />
              <!-- <el-input v-model="temp.faultTime " /> -->
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="duser">
              <el-input v-model="userName" readonly="readonly" placeholder="不填" />
            </el-form-item>
            <!-- <el-form-item label="姓名" prop="duser">

              <el-autocomplete
                v-model="userName"
                class="el-input"
                :fetch-suggestions="userSearchAsync"
                placeholder="请输入工号"
                :trigger-on-focus="false"
                @select="handleSelect"
              />
            </el-form-item> -->
          </el-col>
          <el-col :span="12">
            <el-form-item label="发生时间" prop="happendate">
              <el-date-picker v-model="temp.happendate" type="datetime" value-format="yyyy-MM-dd hh:mm:ss" placeholder="请选择日期" />
              <!-- <el-input v-model="temp.faultTime " /> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="发生地点" prop="happenlocation">
          <el-input v-model="temp.happenlocation" />
        </el-form-item>
        <el-form-item label="灾害预防题目" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>
        <el-form-item label="灾害预防内容" prop="content">
          <markdown-editor ref="markdownEditor" v-model="temp.content" :options="{hideModeSwitch:true,previewStyle:'tab'}" height="300px" />
          <!-- <el-input v-model="temp.content" /> -->
        </el-form-item>
        <el-form-item label="原因" prop="reasonandcon">
          <markdown-editor ref="markdownEditor" v-model="temp.reasonandcon" :options="{hideModeSwitch:true,previewStyle:'tab'}" height="300px" />
          <!-- <el-input v-model="temp.reasonandcon" /> -->
        </el-form-item>
        <el-form-item label="对策" prop="countermeasure">
          <markdown-editor ref="markdownEditor" v-model="temp.countermeasure" :options="{hideModeSwitch:true,previewStyle:'tab'}" height="300px" />
          <!-- <el-input v-model="temp.reasonandcon" /> -->
        </el-form-item>
        <div>
          <span>可能波及程度（保健/安全与环境项目二者选一）</span>
          <table border="1" align="center">

            <tr>
              <td width="500" colspan="2">保健/安全</td>
              <td width="500" rowspan="2">如果处理不及时可能发生保健事故</td>
              <td width="500" colspan="2">环境</td>
            </tr>
            <tr>
              <td width="250">机会损失（万元RMB）</td>
              <td width="250">灾害范围</td>

              <td width="250">对应范围</td>
              <td width="250">灾害范围</td>
            </tr>
            <tr>
              <td><el-input v-model="temp.chanceloss" /></td>
              <td><el-input v-model="temp.disarea" /></td>
              <td><el-date-picker v-model="temp.mayhappendate" type="datetime" value-format="yyyy-MM-dd hh:mm:ss" placeholder="请选择日期" /></td>
              <td><el-input v-model="temp.entoen" /></td>
              <td><el-input v-model="temp.disareae" /></td>

            </tr>
            <tr>
              <td>备注</td>
              <td colspan="4">机会损失：＜1万;1～10万;10～100万;＞100万   灾害范围：单一装置;工艺unit;部门plant;complex
                可能发生保健事故时：可能发生alarm;需要佩戴呼吸装备;从事故地点躲避疏散人员
                对应范围：组;team;防治team;应急组织
              </td>

            </tr>
          </table>

        </div>

        <!-- <el-form-item label="安全灾害范围" prop="disarea">
          <el-input v-model="temp.disarea" />
        </el-form-item>
        <el-form-item label="可能发生灾害事故时间" prop="mayhappendate">
          <el-input v-model="temp.mayhappendate" type="date" placeholder="请选择日期" />
        </el-form-item>
        <el-form-item label="环境对应环境" prop="entoen">
          <el-input v-model="temp.entoen" />
        </el-form-item>
        <el-form-item label="灾害范围" prop="disareae">
          <el-input v-model="temp.disareae" />
        </el-form-item> -->
        <el-form-item label="补充说明及现场简图" prop="contentdetail">
          <markdown-editor ref="markdownEditor" v-model="temp.contentdetail" :options="{hideModeSwitch:true,previewStyle:'tab'}" height="300px" />
          <!-- <el-input v-model="temp.contentdetail" /> -->
        </el-form-item>
        <!-- <el-form-item label="分数" prop="score">
          <el-input v-model="temp.score" />
        </el-form-item> -->
        <!-- <el-form-item label="实施单填写人部门">
        <el-select v-model="deptName" class="filter-item" placeholder="Please select">
          <el-option v-for="item in deptlist" :key="item" :label="item" :value="item" />
        </el-select>
        </el-form-item> -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MarkdownEditor from '@/components/MarkdownEditor'
// import { workOutList, deleteWorkOut, createWorkOut, editWorkOut, fetchAllCount, getPersonList, getDeptList, getFaultNameList } from '@/api/workout'
import { fetchDisasterList, createDisaster, deleteList, fetchAllCount, editDisaster } from '@/api/disaster'
import Sortable from 'sortablejs'
import { parseTime } from '@/utils'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getuserbyemp } from '@/api/user'
import { getDeptByName } from '@/api/fault'
import { getPersonList, getDeptList } from '@/api/fault'
// arr to obj, such as { CN : "China", US : "USA" }
// import Print from 'vue-print-nb'

export default {
  name: 'Disaster',
  components: { Pagination, MarkdownEditor },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }

  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      faultTitle: null,
      editList: null,
      deptName: null,
      userName: null,
      userId: '',
      deptId: '',
      sortable: null,
      oldList: [],
      newList: [],
      // 参数条件
      listQuery: {
        page: 1,
        limit: 20
        // title: '',
        // content: '',
        // disarea: '',
        // createdate: '',
        // happendate: ''
      },
      personlist: null,
      deptlist: null,
      faultNameList: null,
      temp: {
        disid: '',
        title: '',
        content: '',
        disarea: '',
        createdate: '',
        happendate: '',
        happenlocation: '',
        reasonandcon: '',
        chanceloss: '',
        countermeasure: '',
        mayhappendate: '',
        entoen: '',
        disareae: '',
        contentdetail: '',
        duser: '',
        score: '',
        department: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增',
        detail: '明细'

      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        // timestamp: [{ type: 'faultTime', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: '灾害预防题目不能为空', trigger: 'blur' }],
        content: [{ required: true, message: '灾害预防内容不能为空', trigger: 'blur' }],
        createdate: [{ required: true, message: '创建时间不能为空', trigger: 'blur' }],
        happendate: [{ required: true, message: '发生时间不能为空', trigger: 'blur' }],
        happenlocation: [{ required: true, message: '发生位置不能为空', trigger: 'blur' }],
        reasonandcon: [{ required: true, message: '原因及对策不能为空', trigger: 'blur' }],
        countermeasure: [{ required: true, message: '对策不能为空', trigger: 'blur' }],
        contentdetail: [{ required: true, message: '补充说明及现场简图不能为空', trigger: 'blur' }]
        // duser: [{ required: true, message: 'duser is required', trigger: 'blur' }],
        // department: [{ required: true, message: 'department is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  handleFilter() {
    this.listQuery.page = 1
    this.fechData()
  },
  created() {
    getPersonList().then(response => {
      this.personlist = response.listName
    })
    getDeptList().then(response => {
      this.deptlist = response.listName
    })

    this.fechData()
  },
  methods: {
    fechData() {
      fetchDisasterList(this.listQuery).then(response => {
        this.listLoading = true
        this.list = response.disasterList
        this.showList = response.disasterList
        console.log('888888888888888' + response.disasterList)
        this.listLoading = false
        // 获取分页的数据
        fetchAllCount().then(response => {
          this.total = response.count
        })
        // this.oldList = response.map(v => v.id)
      //  this.newList = response.map(v => v.id).slice()
      })
    },

    async handleSelect(u) {
      this.userName = u.userName
      this.userId = u.userId
      // console.log(this.userId)
    },
    async userSearchAsync(queryString, callback) {
      var list = []
      const { userList } = await getuserbyemp(queryString)
      userList.forEach(r => {
        var tem_obj = {}
        tem_obj.value = r.empNo + '-' + r.userName + '-' + r.userId
        tem_obj.userName = r.userName
        tem_obj.userId = r.userId
        list.push(tem_obj)
      })

      callback(list)
      // console.log(queryString)
    },
    async deptSearchAsync(queryString, callback) {
      var list = []
      const { deptList } = await getDeptByName(queryString)
      deptList.forEach(r => {
        var tem_obj = {}
        tem_obj.value = r.deptId + '-' + r.deptName
        tem_obj.deptName = r.deptName
        tem_obj.deptId = r.deptId
        list.push(tem_obj)
      })

      callback(list)
      // console.log(queryString)
    },
    async handleSelectTeam(u) {
      this.deptName = u.deptName
      this.deptId = u.deptId
      // console.log(this.userId)
    },

    resetTemp() {
      this.temp = {
        disid: '',
        title: '',
        content: '',
        disarea: '',
        createdate: '',
        happendate: '',
        happenlocation: '',
        reasonandcon: '',
        chanceloss: '',
        countermeasure: '',
        mayhappendate: '',
        entoen: '',
        disareae: '',
        score: '',
        contentdetail: '',
        duser: '',
        department: ''
      }
    },
    // 新增功能
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      // alert(this.dialogStatus)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 问题所在：select选择后不返回数据到选择框
          // alert(this.userId)
          this.temp.author = 'vue-element-admin'
          // alert('测试时间' + this.temp.createdate)
          const query = { happenlocation: this.temp.happenlocation,
            reasonandcon: this.temp.reasonandcon,
            chanceloss: this.temp.chanceloss,
            countermeasure: this.temp.countermeasure,
            mayhappendate: this.temp.mayhappendate,
            entoen: this.temp.entoen,
            disareae: this.temp.disareae,
            contentdetail: this.temp.contentdetail, title: this.temp.title, content: this.temp.content, disarea: this.temp.disarea, createdate: this.temp.createdate, happendate: this.temp.happendate, userName: this.userName, deptName: this.deptName, userId: this.userId, deptId: this.deptId }
          createDisaster(query).then(() => {
            this.list.unshift(this.temp.userName)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
          // 刷新页面
          location.reload()
        }
      })
    },
    handleDownload() {
      // alert('excel导出')
      // console.log('excel+输出打印数据' + this.list.faultType1)
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['未遂事故编号', '未遂事故题目', '未遂事故类型', '发生地点', '未遂事故发生时间', '未遂事故创建人', '创建人部门']
        const filterVal = ['faultId', 'faultTitle', 'fault_TypeId', 'faultLocation', 'faultTime', 'faultUserCode', 'faultTeam']

        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        }
        if (j === 'faultUserCode') {
          return v[j].userName
        } if (j === 'faultTeam') {
          return v[j].deptName
        } if (j === 'fault_TypeId') {
          // alert(v[j])
          return v[j]
        } else {
          return v[j]
        }
      }))
    },
    showReviewer() {

    },

    handleFilter() {
      this.listQuery.page = 1
      this.fechData()
    },

    handleDelete(row) {
      // alert(row.disid)
      deleteList(row.disid).then(response => {

      })
      // 刷新页面
      location.reload()
      // this.fechData()
    },
    handleEdit(row) {
      const row1 = JSON.parse(JSON.stringify(row))
      this.temp1 = Object.assign({}, row1) // copy obj
      console.log('row1' + row1.duser)
      this.temp.disid = this.temp1.disid
      // alert(this.temp.disid)
      // alert(this.temp1.duser)
      this.userName = this.temp1.duser.userName
      this.deptName = this.temp1.department.deptName

      this.temp.happenlocation = this.temp1.happenlocation
      this.temp.reasonandcon = this.temp1.reasonandcon
      this.temp.chanceloss = this.temp1.chanceloss
      this.temp.countermeasure = this.temp1.countermeasure
      this.temp.mayhappendate = this.temp1.mayhappendate
      this.temp.entoen = this.temp1.entoen
      this.temp.disareae = this.temp1.disareae
      this.temp.contentdetail = this.temp1.contentdetail
      this.temp.title = this.temp1.title
      this.temp.content = this.temp1.content
      this.temp.disarea = this.temp1.disarea
      this.temp.createdate = this.temp1.createdate
      this.temp.happendate = this.temp1.happendate

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      // alert(this.dialogStatus)
      if (this.dialogStatus === 'detail') {
        location.reload()
      } else if (this.dialogStatus === 'update') {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            // const query1 = JSON.parse(JSON.stringify(tempData))

            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            const query = {
              disid: tempData.disid,
              title: tempData.title,
              content: tempData.content,
              disarea: tempData.disarea,
              createdate: tempData.createdate,
              happendate: tempData.happendate,
              happenlocation: tempData.happenlocation,
              reasonandcon: tempData.reasonandcon,
              chanceloss: tempData.chanceloss,
              countermeasure: tempData.countermeasure,
              mayhappendate: tempData.mayhappendate,
              entoen: tempData.entoen,
              disareae: tempData.disareae,
              contentdetail: tempData.contentdetail,
              userName: this.userName, deptName: this.deptName

            }
            editDisaster(query).then(response => {
              this.obj = response
              this.disid = response.disid

              // alert('修改成功')
            })
            // 刷新页面
            location.reload()
          }
        })
      }
    },
    handleDetail(row) {
      const row1 = JSON.parse(JSON.stringify(row))
      this.temp = Object.assign({}, row1)
      this.dialogStatus = 'detail'
      this.userName = this.temp.duser.userName
      this.deptName = this.temp.department.deptName
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      // this.$router.push({ name: 'faultdetail', query: { faultId: row.faultId }})
    },
    handleScore(row) {
      const row1 = JSON.parse(JSON.stringify(row))
      this.temp1 = Object.assign({}, row1) // copy obj

      // alert(this.temp1.faultTitle)
      this.faultType = this.temp1.fault_TypeId.split(',')
      this.userName = this.temp1.faultUserCode.userName
      this.deptName = this.temp1.faultTeam.deptName
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.temp.faultTitle = this.temp1.faultTitle
      this.temp.faultLocation = this.temp1.faultLocation
      this.temp.faultContent = this.temp1.faultContent
      // alert(this.temp1.faultContent)
      this.temp.faultReason = this.temp1.faultReason
      this.temp.faultFun = this.temp1.faultFun
      this.temp.faultRemark = this.temp1.faultRemark
      this.temp.faultadvice = this.temp1.faultadvice
      // this.resetTemp()
      this.dialogStatus = 'score'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    getHtml() {
      this.content = this.$refs.markdownEditor.getHtml()
      this.reasonandcon = this.$refs.markdownEditor.getHtml()
      this.countermeasure = this.$refs.markdownEditor.getHtml()
      this.contentdetail = this.$refs.markdownEditor.getHtml()
      // console.log(this.faultContent)
    },
    // 格式化时间

    // formatJson(filterVal, jsonData) {
    //   return jsonData.map(v => filterVal.map(j => {
    //     if (j === 'timestamp') {
    //       return parseTime(v[j])
    //     } else {
    //       return v[j]
    //     }
    //   }))
    // },

    setSort() {
      const el = this.list[0]

      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)

          // for show the changes, you can delete in you code
          const tempIndex = this.newList.splice(evt.oldIndex, 1)[0]
          this.newList.splice(evt.newIndex, 0, tempIndex)
        }
      })
    }
  }
}
</script>

<style>
.sortable-ghost{
  opacity: .8;
  color: #fff!important;
  background: #42b983!important;
}
</style>

<style scoped>
.icon-star{
  margin-right:2px;
}
.drag-handler{
  width: 20px;
  height: 20px;
  cursor: pointer;
}
.show-d{
  margin-top: 15px;
}
</style>
